<template>
<div>






<div>

</div>
<div class="d-flex justify-content-center p-4">
<b-card
    img-src="https://picsum.photos/600/300/?image=25"
    img-alt="Image"
    img-top
    style="max-width: 30rem;"
    class=""
    > 
    <b-form-input
          id="input-2"
          v-model="sendmsg.title"
          required
          placeholder="请选择下列短信模板或自定义标题"
          class=""
        ></b-form-input>
    <b-form-textarea
      id="textarea"
      v-model="sendmsg.content"
      placeholder="发送内容详情"
      rows="3"
      max-rows="6"
    ></b-form-textarea>
    <div v-if="sendmsg.content">
    <div class="mt-4" ><b-button  v-b-toggle.accordion-1 block class="btn btn-primary">学生列表 {{selected.length>0?'('+selected.length+')人':''}}</b-button></div>
      <b-collapse id="accordion-1" accordion="my-accordion" role="tabpanel" >
        <div  class="p-2">
    <b-form-group >
      <template v-slot:label >
      <div class="d-flex justify-content-start">
        <b-form-checkbox
          v-model="allSelected"
          :indeterminate="indeterminate"
          aria-describedby="flavours"
          aria-controls="flavours"
          @change="toggleAll"
        >
          {{ allSelected ? '全选' : '未全选' }}
        </b-form-checkbox>
      </div>
      </template>
      <div class="d-flex justify-content-start">
      <b-form-checkbox-group
        id="flavors"
        v-model="selected"
        :options="flavours"
        name="flavors"
        class="ml-4"
        aria-label="Individual flavours"
        stacked
      ></b-form-checkbox-group>
    </div>
    </b-form-group>
  </div>
      </b-collapse>
      </div>
</b-card>
</div>





<div class="p-4 mt-4">
<b-card-group deck>
  <b-card 
    :header="value.title" 
    class="text-center" 
    v-for="value in templates" 
    :key="value.title"
    @click="chooseTemplate(value.content,value.title)"
    >
    <b-card-text>{{value.content}}</b-card-text>
  </b-card>
</b-card-group>
</div>

<div class="fixed-bottom p-2" @click="sendMsg()"><b-button  v-if="selected.length!=0" block variant="">发送短信</b-button></div>
</div>
</template>

<script>
//import axios from 'axios'
export default {
  name: 'Upload',
  components: {
  },
  data() {
    return {
    flavours: ['1'],
    selected: [],
    allSelected: false,
    indeterminate: false,

    config:null,
    db:null,
    title:null,
    templates:null,
    classes:null,
    names:[],
    unnames:[],
    allphone:null,
    sendmsg:{
      content:null,
      phones:null,
      title:null
    }
    };
  },
  created:async function(){
  //console.log('form',this.$cookies.get('form'))
    await this.$cloud.auth({ persistence: "local" }).anonymousAuthProvider().signIn()
    this.db = this.$cloud.database();
    //this.config = this.$root.$data.config;
    this.getTemplates();
    if(this.$cookies.get('form')){
      const form = this.$cookies.get('form')
      this.getClass(form.grade,form.inclass);
    }else{
    //无数据,需要重新登录
    }
    //
  },
  mounted: function() {
  },
  methods: {
    async sendMsg(){
    if(this.selected&&this.sendmsg.content){
      this.sendmsg.phones = this.selected.toString();
      //console.log(this.sendmsg)
      
      await this.$cloud.callFunction({
        name: "sendMsg",
        data: this.sendmsg
      }).then(res=>{
        //console.log(res);
        var msg = JSON.parse(res.result.split("&")[0].split("=")[1])
        if(msg == 0){
        this.$bvToast.toast(`发送成功`, {
          title:'Sendmsg',
          autoHideDelay: 2000,
          variant:'success',
          solid: true,
        })
        this.sendmsg.content = ''
        this.selected = [] 
        }else{
        if(msg==15){
          this.$bvToast.toast(`发送失败，请重新发送(15)`, {
          title:'Sendmsg',
          autoHideDelay: 2000,
          variant:'warning',
          solid: true,
        })
        }else{
          this.$bvToast.toast(`发送失败，请重试`, {
          title:'Sendmsg',
          autoHideDelay: 2000,
          variant:'danger',
          solid: true,
        })
        }
        }
      }).catch(()=>{
      this.$bvToast.toast(`发送失败，请重试(error)`, {
          title:'Sendmsg',
          autoHideDelay: 2000,
          variant:'danger',
          solid: true,
        })
      })
      
    }else{
      //信息不全
      console.log('发送信息不全')
    }
      
    },
    async getTemplates(){
      await this.db.collection('templates').get()
      .then(res=>{this.templates = res.data})
      .catch(console.error)
    },
    async getClass(grade,inclass){
      var date = new Date();
      const year = date.getMonth()>=8?date.getFullYear():date.getFullYear()-1;
      const inschool =year-grade+1;
      const $ = this.db.command.aggregate

      await this.db.collection('students').aggregate()
      .match({inschool:inschool,inclass:inclass})
      .group({
        _id: {
          inschool: '$inschool',
          inclass: '$inclass'
        },
        phones: $.addToSet('$phone'),
        students:$.addToSet({text:'$name',value:'$phone'})
      })
      .end()
      .then(res=>{
        //console.log(res.data[0].students)
        this.flavours = res.data[0].students
        this.allphone = res.data[0].phones
        //this.names = res.data[0].names
      })
      /*
      await this.db.collection('students').where({inschool:inschool,inclass:inclass}).get()
      .then(res=>{this.classes = res.data;console.log(res.data)})
      .catch(console.error)
      */
     //await this.db.collection('students').
      //console.log(inschool,inclass);
    },

    /** Triggered by custom 'form-submitted' event from GameForm child component. 
     * Parses formData, and route pushes to 'quiz' with formData as query
     * @public
     */
    handleFormSubmitted(formData) {
      const query = formData
      query.difficulty = query.difficulty.toLowerCase()
      this.$router.push({ name: 'quiz', query: query })
    },
    chooseTemplate(content,title){
      this.sendmsg.content = content;
      this.sendmsg.title = title
      //console.log('1',this.sendmsg.content)
    },
    toggleAll(checked) {
        this.selected = checked ? this.allphone : []
      }
  },
  watch: {
      selected(newVal) {
        // Handle changes in individual flavour checkboxes
        if (newVal.length === 0) {
          this.indeterminate = false
          this.allSelected = false
        } else if (newVal.length === this.flavours.length) {
          this.indeterminate = false
          this.allSelected = true
        } else {
          this.indeterminate = true
          this.allSelected = false
        }
      }
    }
}
</script>
